<template>
  <div class="depot-page">
    <!-- 筛选区 -->
    <el-form :inline="true" :model="page" class="demo-form-inline">
      <el-form-item label="编号">
        <el-input v-model="page.DepotCode" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="仓库名称">
        <el-input v-model="page.DepotName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="部门">
        <el-select v-model="page.Department_Id" placeholder="请选择部门" clearable>
          <el-option v-for="a in Department" :label="a.department_Name" :value="a.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库类型">
        <el-select v-model="page.DTypeId" placeholder="请选择仓库类型">
          <el-option v-for="a in DepotType" :label="a.dTypeName" :value="a.dTypeId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getData">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区 -->
    <div class="action-buttons" style="margin: 10px 0;">
      <el-button type="primary" @click="onAddDepot">新建</el-button>
      <el-button @click="onRefresh">刷新</el-button>
      <!-- <el-button @click="onExport">导出</el-button> -->
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column prop="" type="index" label="序号" width="50" />
      <el-table-column prop="depotCode" label="仓库编号" width="100" />
      <el-table-column prop="depotName" label="仓库名称" width="120" />
      <el-table-column prop="leaseTime" label="租赁时间" width="120">
        <template #default="scoped">
          {{ moment(scoped.row.leaseTime).format('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column prop="dTypeName" label="仓库类型" width="100" />
      <el-table-column prop="department_Name" label="所属部门" width="100" />
      <el-table-column prop="isState" label="是否启用" width="80">
        <template #default="scoped">
          <el-inp v-if="scoped.row.isState == false">禁用</el-inp>
          <el-inp v-if="scoped.row.isState == true">启用</el-inp>
        </template>
      </el-table-column>
      <el-table-column prop="isPreset" label="是否默认" width="80">
        <template #default="scoped">
          <el-inp v-if="scoped.row.isPreset == false">否</el-inp>
          <el-inp v-if="scoped.row.isPreset == true">是</el-inp>
        </template>
      </el-table-column>
      <el-table-column prop="depotAddr" label="地址" width="120" />
      <el-table-column prop="depotArea" label="面积" width="80" />
      <el-table-column prop="contact" label="联系人" width="100" />
      <el-table-column prop="tel" label="电话" width="120" />
      <el-table-column label="操作" width="150">
        <template #default="scoped">
          <el-button type="text" size="small" @click="DepotDel(scoped.row.depotId)">删除</el-button>
          <el-button type="text" size="small" @click="DepotUpdate(scoped.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加 -->
    <el-dialog v-model="dialogTableVisible" title="添加" width="800">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="仓库编号" prop="depotCode">
          <el-input v-model="ruleForm.depotCode" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="depotName">
          <el-input v-model="ruleForm.depotName" />
        </el-form-item>

        <el-form-item label="租赁时间">
          <el-date-picker v-model="ruleForm.leaseTime" type="date" placeholder="请选择租赁时间" clearable />
        </el-form-item>

        <el-form-item label="面积" prop="depotArea">
          <el-input v-model="ruleForm.depotArea" />
        </el-form-item>

        <el-form-item label="部门" prop="dTypeId">
          <el-select v-model="ruleForm.dTypeId" placeholder="请选择部门">
            <el-option v-for="a in Department" :label="a.department_Name" :value="a.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库类型" prop="department_Id">
          <el-select v-model="ruleForm.department_Id" placeholder="请选择仓库类型">
           <el-option v-for="a in DepotType" :label="a.dTypeName" :value="a.dTypeId" />
          </el-select>
        </el-form-item>


        <el-form-item label="联系人" prop="contact">
          <el-input v-model="ruleForm.contact" />
        </el-form-item>
        <el-form-item label="地址" prop="depotAddr">
          <el-input v-model="ruleForm.depotAddr" />
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="ruleForm.tel" />
        </el-form-item>
          <el-form-item label="是否禁用" prop="isState">
          <el-switch v-model="ruleForm.isState" />
        </el-form-item>
        <el-form-item label="是否默认" prop="isPreset">
          <el-switch v-model="ruleForm.isPreset" />
        </el-form-item>
        

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            添加
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
     <!-- 修改 -->
    <el-dialog v-model="dialogTableVisible1" title="修改" width="800">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="仓库编号" prop="depotCode">
          <el-input v-model="ruleForm.depotCode" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="depotName">
          <el-input v-model="ruleForm.depotName" />
        </el-form-item>

        <el-form-item label="租赁时间">
          <el-date-picker v-model="ruleForm.leaseTime" type="date" placeholder="请选择租赁时间" clearable />
        </el-form-item>

        <el-form-item label="面积" prop="depotArea">
          <el-input v-model="ruleForm.depotArea" />
        </el-form-item>

        <el-form-item label="部门" prop="dTypeId">
          <el-select v-model="ruleForm.dTypeId" placeholder="请选择部门">
            <el-option v-for="a in Department" :label="a.department_Name" :value="a.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库类型" prop="department_Id">
          <el-select v-model="ruleForm.department_Id" placeholder="请选择仓库类型">
           <el-option v-for="a in DepotType" :label="a.dTypeName" :value="a.dTypeId" />
          </el-select>
        </el-form-item>


        <el-form-item label="联系人" prop="contact">
          <el-input v-model="ruleForm.contact" />
        </el-form-item>
        <el-form-item label="地址" prop="depotAddr">
          <el-input v-model="ruleForm.depotAddr" />
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="ruleForm.tel" />
        </el-form-item>
          <el-form-item label="是否禁用" prop="isState">
          <el-switch v-model="ruleForm.isState" />
        </el-form-item>
        <el-form-item label="是否默认" prop="isPreset">
          <el-switch v-model="ruleForm.isPreset" />
        </el-form-item>
        

        <el-form-item>
          <el-button type="primary" @click="submitForms()">
            修改
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分页 -->
    <!-- <el-pagination
      background
      layout="prev, pager, next, jumper"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="onPageChange"
      style="margin-top: 16px; text-align: right;"
    /> -->
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import moment from 'moment'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import http from '@/http/axiosHelper'

//显示结果
const tableData = ref([])
const page = ref({
  DepotCode: '',
  DepotName: '',
  DTypeId: '',
  Department_Id: ''
})
const total = ref(20)
const pageSize = ref(10)
const currentPage = ref(1)

onMounted(() => {
  getData();
  getDepartment();//部门下拉框
  getDepotType();//仓库类型
})

const getData = () => {
  http.get("/basicread/api/Depot/GetDepot", { params: page.value }).then(res => {
    tableData.value = res.data.data
  })
}
//刷新
const onRefresh = () => {
  getData();
}
//重置
const onReset = () => {
  page.value.DTypeId = '',
    page.value.Department_Id = '',
    page.value.DepotCode = '',
    page.value.DepotName = ''
  getData();
}
//删除
const DepotDel = (depotId: any) => {
  ElMessageBox.confirm(
    '确定删除仓库管理信息吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      http.get("/basicwrite/api/Depot/DelDepot?DepotId=" + depotId).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg)
          getData();
        }
        else {
          ElMessage.error(res.data.msg)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除被取消',
      })
    })
}
//添加
const dialogTableVisible = ref(false)
const dialogTableVisible1 = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "depotId": 0,
  "depotCode": "",
  "depotName": "",
  "leaseTime": "",
  "dTypeId": '',
  "department_Id": '',
  "isState": true,
  "isPreset": true,
  "depotAddr": "",
  "depotArea": '',
  "contact": "",
  "tel": ""
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  depotCode: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ],
  depotName: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  leaseTime: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
  depotAddr: [
    {
      required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  contact: [
    {
      required: true,
      message: 'Please select a location',
      trigger: 'change',
    },
  ],
  tel: [
    {
      required: true,
      message: 'Please select at least one activity type',
      trigger: 'change',
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      http.post("/basicwrite/api/Depot/AddDepot",ruleForm).then(res=>{
        if(res.data.code==200)
      {
        ElMessage.success(res.data.msg)
        dialogTableVisible.value=false;
        ruleForm.depotCode='',
        ruleForm.depotName='',
        ruleForm.leaseTime='',
        ruleForm.dTypeId='',
        ruleForm.department_Id='',
        ruleForm.depotAddr='',
        ruleForm.depotArea='',
        ruleForm.contact='',
        ruleForm.tel='',
        getData();
      }
      else
      {
        ElMessage.error(res.data.msg);
      }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
//修改
const DepotUpdate = (row: any) => {
  dialogTableVisible1.value = true;
  ruleForm.depotId=row.depotId;
  ruleForm.depotCode = row.depotCode;
  ruleForm.depotName = row.depotName;
  ruleForm.leaseTime = row.leaseTime;
  ruleForm.dTypeId = row.dTypeId; // 关键：反填仓库类型ID
  ruleForm.department_Id = row.department_Id;
  ruleForm.depotAddr = row.depotAddr;
  ruleForm.depotArea = row.depotArea;
  ruleForm.contact = row.contact;
  ruleForm.tel = row.tel;
  ruleForm.isState = row.isState;
  ruleForm.isPreset = row.isPreset;
};
const submitForms=()=>{
  http.post("/basicwrite/api/Depot/UpdateDepot",ruleForm).then(res=>{
    if(res.data.code==200)
  {
    ElMessage.success(res.data.msg)
    dialogTableVisible1.value=false;
    getData();
  }
  else
  {
    ElMessage.error(res.data.msg)
  }
  })
}

//部门下拉框
const Department = ref([{
  "id": '',
  "department_Name": "",
}])
const getDepartment = () => {
  axios.get("/basicread/api/DepartMentAll/ShowDepartMent").then(res => {
    Department.value = res.data.data
  })
}
//仓库类型
const DepotType = ref([{
  "dTypeId": 0,
  "dTypeName": ""
}])
const getDepotType = () => {
  http.get("/basicread/api/Depot/GetDepotType").then(res => {
    DepotType.value = res.data.data
  })
}
function onSelectionChange(val: any) { }

function getNextDepotCode() {
  if (!tableData.value.length) return 'CK001';
  // 提取所有编号中的数字部分
  const codes = tableData.value
    .map((item: any) => item.depotCode)
    .filter((code: string) => /^CK\d{3}$/.test(code))
    .map((code: string) => parseInt(code.slice(2), 10));
  const max = codes.length ? Math.max(...codes) : 0;
  const next = (max + 1).toString().padStart(3, '0');
  return `CK${next}`;
}

function onAddDepot() {
  ruleForm.depotCode = getNextDepotCode();
  // 其余字段清空
  ruleForm.depotName = '';
  ruleForm.leaseTime = '';
  ruleForm.dTypeId = '';
  ruleForm.department_Id = '';
  ruleForm.depotAddr = '';
  ruleForm.depotArea = '';
  ruleForm.contact = '';
  ruleForm.tel = '';
  ruleForm.isState = true;
  ruleForm.isPreset = true;
  dialogTableVisible.value = true;
}
</script>

<style scoped>
.depot-page {
  padding: 20px;
  background: #fff;
}

.search-form {
  margin-bottom: 10px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
